<?php

namespace addons\mental\controller;

use addons\mental\model\TestMain;
use addons\mental\model\Testlog as testLogModel;
use addons\mental\model\ResultItem;
use addons\mental\model\Testson;
use addons\mental\model\Order;
use think\Log;
use think\Db;

class Testlog extends Base
{
    protected $noNeedLogin = ['mark_result','test_result','priceList'];

    /**
     * Undocumented function
     * 跳转类型的结果提交
     * @return void
     */
    public function skip_result()
    {
        $test_id = $this->request->param('test_id'); //记录id
        $number = $this->request->param('number'); //结果序号
        $content = $this->request->param('content'); //答题过程
        if (!$test_id || !$number || !$content) {
            $this->error(__('Invalid parameters'));
        }
        $testLogModel = new testLogModel();
        $test_log = $testLogModel->where('id', '=', $test_id)->where('user_id', '=', $this->auth->id)->find();
        if (empty($test_log)) {
            $this->error(__('No results were found'));
        }
        //状态已完成
        if ($test_log->status == 'finish') {
            $this->error(__('Operation failed'));
        }
        $testMain = new TestMain();
        $test = $testMain->where('switch',1)->where('id',$test_log->main_id)->find();
        if (empty($test)) {
            $this->error(__('No results were found'));
        }
        //查结果
        $resultItem = new ResultItem();
        $result = $resultItem->where('main_id', '=', $test_log->main_id)->where('number', '=', $number)->find();
        if (empty($result)) {
            $this->error(__('No results were found'));
        }

        $test_log->title = $result->title;
        $test_log->content = $result->content;
        $test_log->result_log = $content;
        $test_log->type = $test->type;
        $test_log->status = 'finish';
        $test_log->save();
        //完成，测试累加 1
        $test->test_num += 1;
        $test->save();

        $this->success(__('Operation completed'));
    }

    /**
     * Undocumented function
     * 打分类型结果提交
     * @return void
     */
    public function mark_result()
    {
        $test_id = $this->request->param('test_id'); //记录id
        $result = $this->request->param('result'); //答题结果
        if (!$test_id || !$result) {
            $this->error(__('Invalid parameters'));
        }
        $result_arr = json_decode(html_entity_decode($result), true);
        // halt($result_arr);

        $testLogModel = new testLogModel();
        $test_log = $testLogModel->field('user_id,main_id,title,content,status,invitation_code,age')
            ->where('id', '=', $test_id)
            // ->where('user_id', '=', $this->auth->id) 
            ->find();
        if (empty($test_log)) {
            $this->error(__('No results were found'));
        }
        //状态已完成
        if ($test_log->status == 'finish') {
            $this->error(__('Operation failed'));
        }
        
        if ($test_log->invitation_code) {
            $data = \think\Db::name('mental_invitationcode')->where(['invitation_code'=>$test_log->invitation_code])->find();
            if (!$data) {
                $this->error('邀请码不存在');
            }
            $num = $data['num'] - $data['used_num'];
            if ($num<=0) {
                $this->error('邀请码使用次数已用完');
            }
        }
        
        
        
        
        $testMain = new TestMain();
        $test = $testMain->where('switch',1)->where('id',$test_log->main_id)->find();
        if (empty($test)) {
            $this->error(__('No results were found'));
        }
        //去统计分数
        $testson = new Testson();
        try {
            $score = $testson->totalScore($test_log->main_id, $result_arr);
        } catch (\Exception $e) {
            $this->error('分数计算出错！' . $e->getMessage());
        }
        if ($score == -1) {
            $this->error(__('Operation failed'));
        }

        //根据分数，匹配结果
        // $resultItem = new ResultItem();
        // $test_result = $resultItem->field('title,content')
        //     ->where('left', '<=', $score)
        //     ->where('right', '>', $score)
        //     ->where('main_id', '=', $test_log->main_id)
        //     ->find();

        // if (empty($test_result)) {
        //     $this->error(__('No results were found1111'));
        // }
        \addons\mental\model\TestMainStatistics::setIncNum($test_log->main_id, 4);
        //记录更新
        $test_log->title = '';
        $test_log->content = '';
        $test_log->result_log = $result;
        $test_log->type = $test->type;
        $test_log->status = 'finish';
        // halt($test_log->toArray())
        $test_log->save();
        //完成，测试累加 1
        $test->test_num += 1;
        $test->save();
        
        $this->success(__('Operation completed'));
    }

    /**
     * @Description 量表测试
     */
    public function liang_result()
    {
        $test_id = $this->request->param('test_id'); //记录id
        $result = $this->request->param('result'); //答题结果
        if (!$test_id || !$result) {
            $this->error(__('Invalid parameters'));
        }
        $result_arr = json_decode(html_entity_decode($result), true);
        $testLogModel = new testLogModel();
        $test_log = $testLogModel->field('user_id,main_id,title,content,status')
            ->where('id', '=', $test_id)
            ->where('user_id', '=', $this->auth->id)
            ->find();
        if (empty($test_log)) {
            $this->error(__('No results were found'));
        }
        //状态已完成
        if ($test_log->status == 'finish') {
            $this->error(__('Operation failed'));
        }
        $testMain = new TestMain();
        $test = $testMain->where('switch',1)->where('id',$test_log->main_id)->find();
        if (empty($test)) {
            $this->error(__('No results were found'));
        }
        $arr = [];
        $question_ids = [];
        foreach ($result_arr as $item) {
            $arr[$item['component_id']][] = $item;
            $question_ids[$item['question_id']] = $item['question_id'];
        }
        //去统计分数
        $testson = new Testson();
        $score_list = $testson->liangTotal($test_log->main_id, $arr, $question_ids);
        if (empty($score_list)) {
            $this->error(__('Operation failed'));
        }
        //根据分数，匹配结果
        $resultItem = new ResultItem();
        $test_result = $resultItem
            ->where('main_id', '=', $test_log->main_id)
            ->select();

        if (empty($test_result)) {
            $this->error(__('No results were found'));
        }
        $all_result = [];
        foreach ($score_list as $key => $res) {
            $all_result[$key] = $this->results($key, $res['score'], $test_result);
        }
        //记录更新     
        $test_log->content = json_encode($all_result);
        $test_log->result_log = $result;
        $test_log->status = 'finish';
        $test_log->type = $test->type;
        $test_log->save();
        //完成，测试累加 1
        $test->test_num += 1;
        $test->save();
        $this->success(__('Operation completed'));
    }


    private function results($component_id, $score, $list)
    {
        $result = [];
        foreach ($list as $item) {
            if ($item['component_id'] == $component_id && $item['left'] <= $score && $item['right'] > $score) {
                $result = [
                    'result_id' => $item['result_id'],
                    'main_id' => $item['main_id'],
                    'component_id' => $item['component_id'],
                    'title' => $item['title'],
                    'content' => $item['content']
                ];
            }
        }
        return $result;
    }


    /**
     * Undocumented function
     * 测试结果
     * @return void
     */
    public function test_result()
    {
        $test_id = $this->request->param('test_id'); //记录id
        if (!$test_id) {
            $this->error(__('Invalid parameters'));
        }
        $uid = $this->auth->id??0;
        $testLogModel = new testLogModel();
        $test_log = $testLogModel->detail($test_id, $uid);
        // halt($test_log->testreportData1);
        if (empty($test_log)) {
            $this->error(__('No results were found'));
        }

      
        $test_log->isReport = 1;//1=完整版,2=非完整版,3=指只能看报告
        $test_log->isManualInterpretation = true;//专业人工解读
        if($test_log['main_id']==25){
            $test_log->content = '答案其实很简单，就是用你的潜意识告诉你最想要的是什么。
不知道自己要什么，这是很普遍的问题，因为什么都挺重要的，舍弃什么都不成体统，只是每个人的人生追求确实差异很大，看别人追求事业，你也羡慕也很想这样，但不知道为什么总做不到；看别人婚姻幸福，你也很想，可实现起来确实不容易，这和运气也不是太有关系，而是你需要的决定了很多。
很多受测的朋友其中选择E为首的占大多数，说明事业对不少来说人还是很重要的，还有距离问题，比如你选择了事业和金钱互相挨着，这很正常，这两项都是有关联的，可如果你把爱情排第一，却又把家庭排最后，那就说明，你未必会依赖婚姻这个形式，这排列组合是可以推理的。我想这个东西确实预示性很强，你要什么肯定会下意识地追求了什么。
M——金钱（Money）
L——爱情（Love）
S——性（Sex）
F——家庭（Family）
E——事业（Enterprise）';
        }
        //抑郁症
        if($test_log['main_id']==26){
            if($test_log['total_score']<17){
                $test_log->content = '您的测试得分为'.$test_log['total_score'].',没有抑郁症，请继续保持。';
            }
            if($test_log['total_score']>17 && $test_log['total_score']<20){
                $test_log->content = '您的测试得分为'.$test_log['total_score'].',您正处在抑郁症的边缘。';
            }
            if($test_log['total_score']>20){
                $test_log->content = '您的测试得分为'.$test_log['total_score'].',建议您找专业人员咨询或诊断。';
            }
        }
        //reportType 订单类型:1=结果+完整解读,2=只看测试结果,3=专业人工解读
        if ($test_log->invitation_code == "") {
            if ($test_log['pay_mode'] == 1) {//判断是否是付费查看结果
            
                $test_log->isReport = 3;
                
                $order = (new Order())->where('test_id', $test_id)->where('status', 'paid')->where(function ($query) {
                    $query->where('type', 1)->whereOr('type', 5)->whereOr('type', 3);
                })->find();
                // var_dump($order);die;
                if ($order) {
                    $test_log->isReport = 1;
                }else {
                    $order = (new Order())->where('test_id', $test_id)->where('status', 'paid')->where('type',2)->find();
                    if ($order) {
                        $test_log->isReport = 2;
                        
                    }
                    
                    //赠送他人测试
                    $order = (new Order())->where('test_id', $test_id)->where('status', 'paid')->where('type',4)->find();
                    if ($order) {
                        $test_log->isReport = 1;
                        
                    }
                }
                
                
                $order = (new Order())->where('test_id', $test_id)->where('status', 'paid')->where('type',3)->find();
                if (!$order) {
                    $test_log->isManualInterpretation = false;
                }
                
            }
           
        }
        
        $testreportData = $test_log->testreportData2;
        
    
        if ($test_log->isReport == 2) {
            $testreportData = [
                            $testreportData[0]??'',
                            $testreportData[1]??'',
                            $testreportData[2]??'',
                            $testreportData[3]??'',
                        ];
        }elseif ($test_log->isReport == 3) {
            $testreportData = [];
        }
        
        
        $qzdfxqtImgArr = [];
        $test_log->qzdfxqtImgArr = $qzdfxqtImgArr;//气质类型得分详情图
        $test_log->testreportData = $testreportData;
        $rotationImgArr = explode(',',$test_log->rotationImg);
        foreach ($rotationImgArr as $k=>$v){
            $rotationImgArr[$k]="https://".$_SERVER['HTTP_HOST'].$v;
        }
        $test_log->rotationImg = (array)$rotationImgArr;
        $ret = $test_log->toArray();
        unset($ret['testreportData2']);
        
        $ret['updatetime'] = date('Y-m-d H:i:s',$ret['updatetime']);
        // echo $_SERVER['HTTP_HOST'];
        $this->success(__('Operation completed'), $ret);
    }
    
    /**
     * 量表价格数据
     * addons/mental/testlog/priceList
     * @param int $test_id 记录id
     */
    public function priceList()
    {
        $test_id = $this->request->param('test_id'); //记录id
        
        
        $arr = \think\Db::name('mental_testlog')->alias('l')->join('mental_testmain m','l.main_id=m.id')->where('l.id',$test_id)->field('l.id as test_id,m.price,m.original_price,m.price1,m.original_price1,m.price2,m.original_price2,m.priceTitle,m.priceInfo,m.priceTitle1,m.priceInfo1,m.priceTitle2,m.priceInfo2,m.price3')->find();
        $arr['isBy'] = true;
        $order = (new Order())->where('test_id', $test_id)->where('status', 'paid')->where('type',2)->find();
        if (!$order) {
            $arr['isBy'] = false;
        }
        $this->success('成功',$arr);
        
    }

    /**
     * Undocumented function
     * 我的测试
     * @return void
     */
    public function my_test()
    {
        $param = $this->request->param();
        $param['user_id'] = $this->auth->id;
        $param['status'] = 'finish';
        $testLogModel = new testLogModel();
        $list = $testLogModel->tableList($param);
        if (!$list->total()) {
            $this->error(__('No results were found'));
        }
        foreach ($list as $key=>&$value){
            $value['image'] = compatImage($value['image']);
            $value['order'] = Order::where(['test_id'=>$value['id']])->find();
        }
        $this->success(__('Operation completed'), $list);
    }
}
